/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rpc.remote.grpc;
//import io.grpc.protobuf.lite.
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptor;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GrpcServer {
    int port = 5401;

    int maxInboundMetadataSize = 64*1024;

    int maxInboundMessageSize = 64*1024*1024;

    private ServerBuilder<?> serverBuilder;

    private Server server;

    private List<BindableService> grpcServices = new ArrayList<>();

    private List<ServerInterceptor> interceptors = new ArrayList<>();

    /**
     * @param port 服务端占用的端口
     */
    public GrpcServer(int port) {
        //手动设置server
        //最大请求长度、最大头长度
        serverBuilder = ServerBuilder.forPort(port).maxInboundMetadataSize(64*1024).maxInboundMessageSize(64*1024*1024);
                // 将具体实现的服务添加到gRPC服务中
//                .addService(new GrpcServerInvoke())
//                .build();
    }

    /**
     * grpc服务注册
     * @param bindableService
     */
    public void registerGrpcService(BindableService bindableService){
        grpcServices.add(bindableService);
        serverBuilder = serverBuilder.addService(bindableService);
    }

    public boolean ifRegistered(){
        return grpcServices!=null&&grpcServices.size()!=0;
    }

    /**
     * grpc服务端拦截器注册
     * @param interceptor
     */
    public void registerInterceptor(ServerInterceptor interceptor){
        interceptors.add(interceptor);
        serverBuilder = serverBuilder.intercept(interceptor);
    }

    public void buildServer(){
        server = serverBuilder.build();
    }

    public void start() throws IOException {
        server.start();
    }

    public void shutdown() {
        server.shutdown();
    }
}
